package com.teddy.DTXMB.Service.Impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.teddy.DTXMB.Mapper.OrderMapper;
import com.teddy.DTXMB.Model.Custom;
import com.teddy.DTXMB.Model.Order;
import com.teddy.DTXMB.Model.OrderList;
import com.teddy.DTXMB.Model.ShoppingCart;
import com.teddy.DTXMB.Service.OrderService;

@Service
public class OrderServiceImpl implements OrderService {
	
	@Autowired
	private OrderMapper orderMapper;

	@Override
	public List<Order> getAllOrderByCustomID(int id) {
		return orderMapper.selectAllOrderByCustomID(id);
	}

	@Override
	public List<Order> getOrdersByPageID(int customID, int pageNumber) {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customID", customID);
		map.put("pageNumber", pageNumber * 5);
		
    	List<Order> orders = orderMapper.selectOrdersByPageNumber(map);
		return orders;
	}

	@Override
	public Order getOrderByID(int id) {
		return orderMapper.selectOrderByID(id);
	}

	@Override
	public List<OrderList> getOrderListByOrderID(int id) {
		return orderMapper.selectOrderListByOrderID(id);
	}

	@Override
	public int makeShoppingCartToOrder(Custom custom, List<ShoppingCart> shoppingCarts) {
		Order order = new Order();
    	order.setCustomid(custom.getId());
    	order.setCreatetime(new Date());
    	order.setUpdatetime(new Date());
    	order.setStatus(1);
    	
    	double amout = 0.0;
    	for(ShoppingCart sc : shoppingCarts){
    		amout = amout + (sc.getPrice() * sc.getProductnumber());
    	}
    	order.setAmout(amout);
		
    	int newOrderID = 0;
		
    	int result = orderMapper.addOneNewOrder(order);
    	
    	if(result > 0){
    		newOrderID = order.getId();
        	
        	for(ShoppingCart sc : shoppingCarts){
        		OrderList oList = new OrderList();
        		oList.setOrderid(newOrderID);
        		oList.setProductid(sc.getProductid());
        		oList.setProductnumber(sc.getProductnumber());
        		orderMapper.addOneNewOrderList(oList);	
        	}
        	return newOrderID;
    	}
    	else{
    		return 0;
    	}
	}
}
